<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
	<div class="title" align="center"><h2>Product scraping</h2></div>
	<div class="form">
		<form id="product_info" name="product_info" method="post" action="index.php" style="width: 100%; margin-left: 30%">
			<label for="product_id">Enter product id: </label>
			<input type="text" id="product_id" name="product_id" />
			<input type="submit" name="btnSubmit" value="Show information" />
		</form>
	</div>
	<div class="message" align="center" style="color: blue; margin-top: 1%;"><?php if(isset($_GET['message'])) echo $_GET['message'];?></div>
<?php
	require_once('../libs/lsamp_curl.php');
	$message = '';
	$get_link = 'http://casiberia.com/product_details.asp?id=';
	if(isset($_POST['btnSubmit'])){
		if(isset($_POST['product_id'])){
			$product_id = $_POST['product_id'];
			$get_link .= $product_id;
			$http_client = new lsamp_cURL(FALSE,'','gzip','','', 30);						
			$html = $http_client->get($get_link, $errno, $error);
			if($errno != 0){
				$message .= 'Failed to touch the link: ' . $link . ". Error: " . $error;
			}else{
				$pattern = "/<b>SUGGESTED RETAIL PRICE: ([^<]+)<br>([^<]+)/";
				if(preg_match($pattern, $html, $matches)){
					$message .= "Suggested retail price: " . $matches[1];
					$message .= " -- ";
					if(strstr($matches[2], "In stock")){
						$message .= "<i><font color=\"green\">In stock</font></i>";
					}else{						
						$message .= "<i><font color=\"red\">Out of stock</font></i>";
					} 
				}else{
					$message .= "The site has changed its format";
				}
			}			
		}else{
			$message = "No product id specified";
		}
		header("Location: index.php?message=" . urlencode($message));
	} 
?>
</body>
</html>